<template>
  <form class="profile-form" @submit.prevent="handleSubmit">
    <div class="form-header">
      <h3>编辑个人信息</h3>
      <p>请完善您的个人信息，带 <span class="required">*</span> 的为必填项</p>
    </div>

    <div class="form-grid">
      <!-- 原有的个人信息表单保持不变 -->
      <div class="form-group">
        <label class="form-label">用户名</label>
        <input
          type="text"
          v-model="formData.username"
          class="form-control"
          disabled
        >
        <div class="form-hint">用户名不可修改</div>
      </div>

      <div class="form-group">
        <label class="form-label">年级 <span class="required">*</span></label>
        <input
          type="text"
          v-model="formData.grade"
          class="form-control"
          required
          placeholder="例如：2024"
          maxlength="20"
        >
        <div class="form-hint">请输入您的年级，如：2024</div>
      </div>

      <div class="form-group">
        <label class="form-label">专业 <span class="required">*</span></label>
        <input
          type="text"
          v-model="formData.major"
          class="form-control"
          required
          placeholder="例如：计算机科学与技术"
          maxlength="50"
        >
        <div class="form-hint">请输入您的专业</div>
      </div>

      <div class="form-group">
        <label class="form-label">手机号码</label>
        <input
          type="tel"
          v-model="formData.phone"
          class="form-control"
          maxlength="11"
          pattern="1[3-9]\d{9}"
          placeholder="请输入11位手机号码"
        >
        <div class="form-hint">请输入11位手机号码</div>
      </div>

      <div class="form-group">
        <label class="form-label">邮箱</label>
        <input
          type="email"
          v-model="formData.email"
          class="form-control"
          placeholder="请输入有效的邮箱地址"
        >
        <div class="form-hint">请输入有效的邮箱地址</div>
      </div>

      <div class="form-group full-width">
        <label class="form-label">部门/院系</label>
        <input
          type="text"
          v-model="formData.department"
          class="form-control"
          maxlength="50"
          placeholder="请输入您的部门或院系"
        >
      </div>

      <div class="form-group">
        <label class="form-label">用户角色</label>
        <input
          type="text"
          v-model="formData.role"
          class="form-control"
          disabled
        >
      </div>
    </div>

    <!-- 🎯 修改密码区域 -->
    <div class="password-section">
      <h4 class="section-title">修改密码</h4>
      <div class="password-grid">
        <div class="form-group">
          <label class="form-label">原密码 <span class="required">*</span></label>
          <input
            type="password"
            v-model="passwordForm.oldPassword"
            class="form-control"
            placeholder="请输入当前密码"
            required
          >
          <div class="form-hint">请输入您当前使用的密码</div>
        </div>

        <div class="form-group">
          <label class="form-label">新密码 <span class="required">*</span></label>
          <input
            type="password"
            v-model="passwordForm.newPassword"
            class="form-control"
            placeholder="请输入新密码"
            required
          >
          <div class="form-hint">输入您想要设置的新密码</div>
        </div>
      </div>

      <div class="password-actions">
        <button
          type="button"
          class="btn-change-password"
          @click="handlePasswordChange"
          :disabled="!isPasswordFormValid"
        >
          <span class="btn-text">修改密码</span>
          <span class="btn-icon">🔒</span>
        </button>
      </div>
    </div>

    <div class="form-actions">
      <button type="submit" class="btn-save">
        <span class="btn-text">保存个人信息</span>
        <span class="btn-icon">💾</span>
      </button>
      <button type="button" class="btn-cancel" @click="resetForm">
        <span class="btn-text">取消</span>
        <span class="btn-icon">↩️</span>
      </button>
    </div>
  </form>
</template>

<script setup lang="ts">
import { ref, watch, computed } from 'vue';
import { request } from '@/utils/request.ts';

// 定义用户信息类型 - 与父组件保持一致
interface UserInfo {
  userId: number;  // 🎯 改为 userId 保持一致性
  username: string;
  phone: string;
  email: string;
  department: string;
  role: string;
  grade: string;
  major: string;
}

// 密码表单类型
interface PasswordForm {
  oldPassword: string;
  newPassword: string;
}

// 定义后端响应类型
interface ApiResponse {
  success: boolean;
  message?: string;
}

// 接收父组件传入的用户信息
const props = defineProps<{
  userInfo: UserInfo;
}>();

// 定义事件
const emit = defineEmits<{
  (e: 'save-success'): void;
  (e: 'save-error', message: string): void;
  (e: 'cancel'): void;
}>();

// 表单数据
const formData = ref<UserInfo>({
  userId: 0,
  username: '',
  phone: '',
  email: '',
  department: '',
  role: '',
  grade: '',
  major: ''
});

// 密码表单数据
const passwordForm = ref<PasswordForm>({
  oldPassword: '',
  newPassword: ''
});

// 保存原始数据用于重置
const originalData = ref<UserInfo>({...formData.value});

// 检查密码表单是否有效
const isPasswordFormValid = computed(() => {
  const { oldPassword, newPassword } = passwordForm.value;
  return oldPassword.trim() !== '' && newPassword.trim() !== '';
});

// 监听props变化，同步到表单
watch(
  () => props.userInfo,
  (newVal) => {
    console.log('ProfileForm接收到用户信息:', newVal);
    if (newVal) {
      formData.value = {...newVal};
      originalData.value = {...newVal};
    }
  },
  { immediate: true, deep: true }
);

// 个人信息表单验证
const validateForm = (): string[] => {
  const errors: string[] = [];

  if (!formData.value.grade?.trim()) {
    errors.push('年级为必填项');
  }

  if (!formData.value.major?.trim()) {
    errors.push('专业为必填项');
  }

  return errors;
};

// 密码表单验证
const validatePasswordForm = (): string[] => {
  const errors: string[] = [];
  const { oldPassword, newPassword } = passwordForm.value;

  if (!oldPassword.trim()) {
    errors.push('请输入原密码');
  }

  if (!newPassword.trim()) {
    errors.push('请输入新密码');
  }

  return errors;
};

// 提交个人信息表单
const handleSubmit = async (): Promise<void> => {
  const errors = validateForm();
  if (errors.length > 0) {
    alert(errors.join('\n'));
    return;
  }

  try {
    const updateData = {
      email: formData.value.email || '',
      phone: formData.value.phone || '',
      department: formData.value.department || '',
      grade: formData.value.grade || '',
      major: formData.value.major || ''
    };

    console.log('提交个人信息更新:', updateData);
    console.log('用户ID:', formData.value.userId);

    // 🎯 修复：检查 userId 是否存在
    if (!formData.value.userId) {
      alert('用户ID不存在，无法更新信息');
      return;
    }

    const response: ApiResponse = await request.put('/api/user/update', updateData, {
      params: {
        userId: formData.value.userId
      }
    });

    console.log('个人信息更新响应:', response);

    if (response.success) {
      console.log('个人信息更新成功');
      emit('save-success');
    } else {
      const errorMessage = response.message || '更新信息失败';
      console.log('个人信息更新失败:', errorMessage);
      emit('save-error', errorMessage);
    }
  } catch (error: unknown) {
    console.error('更新用户信息失败:', error);

    // 🎯 安全地处理错误
    if (error instanceof Error) {
      emit('save-error', error.message);
    } else {
      emit('save-error', '网络错误，更新失败');
    }
  }
};

// 处理密码修改
const handlePasswordChange = async (): Promise<void> => {
  const errors = validatePasswordForm();
  if (errors.length > 0) {
    alert(errors.join('\n'));
    return;
  }

  try {
    const passwordData = {
      oldPassword: passwordForm.value.oldPassword,
      newPassword: passwordForm.value.newPassword
    };

    console.log('提交密码修改:', passwordData);
    console.log('用户ID:', formData.value.userId);

    // 🎯 修复：检查 userId 是否存在
    if (!formData.value.userId) {
      alert('用户ID不存在，无法修改密码');
      return;
    }

    const response: ApiResponse = await request.put('/api/user/update', passwordData, {
      params: {
        userId: formData.value.userId
      }
    });

    console.log('密码修改响应:', response);

    if (response.success) {
      alert('密码修改成功！');
      // 清空密码表单
      passwordForm.value = {
        oldPassword: '',
        newPassword: ''
      };
      emit('save-success');
    } else {
      const errorMessage = response.message || '密码修改失败';
      alert(errorMessage);
      emit('save-error', errorMessage);
    }
  } catch (error: unknown) {
    console.error('修改密码失败:', error);

    // 🎯 安全地处理错误，不使用 any
    let errorMessage = '网络错误，密码修改失败';
    if (error instanceof Error) {
      errorMessage = error.message;
    }

    alert(errorMessage);
    emit('save-error', errorMessage);
  }
};

// 重置表单
const resetForm = (): void => {
  formData.value = {...originalData.value};
  passwordForm.value = {
    oldPassword: '',
    newPassword: ''
  };
  emit('cancel');
};
</script>

<style scoped>
.profile-form {
  width: 100%;
}

.form-header {
  text-align: center;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 2px solid #f0f2f5;
}

.form-header h3 {
  color: #2c3e50;
  margin: 0 0 10px 0;
  font-size: 1.5rem;
  font-weight: 600;
}

.form-header p {
  color: #666;
  margin: 0;
  font-size: 14px;
}

.form-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
  margin-bottom: 30px;
}

.form-group {
  display: flex;
  flex-direction: column;
}

.form-group.full-width {
  grid-column: 1 / -1;
}

.form-label {
  display: block;
  margin-bottom: 8px;
  color: #495057;
  font-weight: 500;
  font-size: 14px;
}

.required {
  color: #ff4d4f;
  font-weight: bold;
}

.form-control {
  width: 100%;
  padding: 12px 15px;
  border: 2px solid #e9ecef;
  border-radius: 8px;
  font-size: 14px;
  transition: all 0.3s ease;
  background: #fff;
}

.form-control:focus {
  outline: none;
  border-color: #31B310;
  box-shadow: 0 0 0 3px rgba(49, 179, 16, 0.1);
  transform: translateY(-1px);
}

.form-control:disabled {
  background-color: #f8f9fa;
  color: #6c757d;
  cursor: not-allowed;
  border-color: #dee2e6;
}

.form-control::placeholder {
  color: #adb5bd;
}

.form-hint {
  margin-top: 6px;
  font-size: 12px;
  color: #6c757d;
  line-height: 1.4;
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #f0f2f5;
}

.btn-save, .btn-cancel {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 24px;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 16px;
  font-weight: 500;
  transition: all 0.3s ease;
  min-width: 120px;
  justify-content: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.btn-save {
  background: linear-gradient(to right, #31B310, #2a990e);
  color: white;
}

.btn-save:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
  background: linear-gradient(to right, #2a990e, #248f0c);
}

.btn-cancel {
  background: linear-gradient(to right, #6c757d, #5a6268);
  color: white;
}

.btn-cancel:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
  background: linear-gradient(to right, #5a6268, #495057);
}

.btn-text {
  font-weight: 500;
}

.btn-icon {
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .form-grid {
    grid-template-columns: 1fr;
    gap: 15px;
  }

  .form-actions {
    flex-direction: column;
    gap: 10px;
  }

  .btn-save, .btn-cancel {
    width: 100%;
  }
}
</style>
